package com.zlzxm.studentscreen.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.zlzxm.studentscreen.net.websocket.ClassRoomAdapter;
import com.zlzxm.studentscreen.net.websocket.ClassRoomServer;
import com.zlzxm.studentscreen.net.websocket.message.CodeContent;
import com.zlzxm.studentscreen.net.websocket.message.PlayContent;
import com.zlzxm.studentscreen.net.websocket.message.WebSocketMessage;
import com.zlzxm.studentscreen.util.ToastyUtil;


import org.java_websocket.handshake.ServerHandshake;

/**
 * CREATE BY zlzxm ON 2/5/21
 * 后端服务 这里主要有长连接管理 和 设备各种信息广播注册
 */
public class CoreService extends Service {
    public static final String  CLASSROOM_URL = "url";
    private static final String TAG = "WebSocketService";

    public static final String SEND_SCREEN_CODE = "SEND_SCREEN_CODE";
    public static final String PLAYER_SCREEN = "PLAYER_SCREEN";
    public static final String CLOSE_SCREEN = "CLOSE_SCREEN";



    private ClassRoomServer classRoomServer;

    private  MyAdapter adapter;

    private  Handler handler;

    private  AudioManager am;


    private LocalBroadcastManager localBroadcastManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG,"onCreate");
        localBroadcastManager = LocalBroadcastManager.getInstance(this);

        handler = new Handler();
        adapter = new MyAdapter();
        classRoomServer = ClassRoomServer.getInstance();

        classRoomServer.addClassRoomListener(adapter);

        am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
    }




    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG,"onStartCommand");

        if(intent != null) {

            String url = intent.getStringExtra(CLASSROOM_URL);

            if (!TextUtils.isEmpty(url)) {

                classRoomServer.connect(url);

            }

        }else {

            //当被强行杀死复活时

            connectToLocalRoomServer();


        }


        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.e(TAG,"onDestroy");
        super.onDestroy();
        if(adapter != null && classRoomServer != null){

            classRoomServer.removeClassRoomListener(adapter);

            classRoomServer.close();
        }

    }


    private void connectToLocalRoomServer(){

//        String url = null;
//
//        RoomInfo roomInfo = MMKV.defaultMMKV().decodeParcelable(Constant.MMKVKey.ROOM_INFO,
//                RoomInfo.class);
//
//        if(roomInfo != null){
//
//            url = roomInfo.getRoomServer();
//        }
//
//        if (!TextUtils.isEmpty(url)) {
//
//            classRoomServer.connect(url);
//
//        }

    }







    class MyAdapter extends ClassRoomAdapter {

        public static final String MARK = "event";

        @Override
        public void onWebSocketOpen(ServerHandshake handShakeData) {
            super.onWebSocketOpen(handShakeData);
            Log.e(MARK,"onOpen");


            handler.post(new Runnable() {
                @Override
                public void run() {
                    ToastyUtil.succeedToast(CoreService.this,"socket:客户端连接成功");
                }
            });
        }

        @Override
        public void onWebSocketClose(int code, String reason, boolean remote) {
            super.onWebSocketClose(code, reason, remote);

        }

        @Override
        public void onWebSocketError(Exception ex){
            super.onWebSocketError(ex);
            Log.e(MARK,"onError :" + ex.getMessage());

        }


        @Override
        public void onMessage(String msg) {
            super.onMessage(msg);
            if(msg.equals("pong")){
                return;
            }
            WebSocketMessage webSocketMessage = JSON.parseObject(msg,WebSocketMessage.class);
            if(webSocketMessage.getMessageType().equals(SEND_SCREEN_CODE)){
                //
                Intent intent = new Intent();
                intent.setAction(SEND_SCREEN_CODE);
                intent.putExtra(SEND_SCREEN_CODE,JSON.parseObject(webSocketMessage.getMessageBody(),CodeContent.class).getCode());
                localBroadcastManager.sendBroadcast(intent);
            }else if(webSocketMessage.getMessageType().equals(PLAYER_SCREEN)){

                Intent intent = new Intent();
                intent.setAction(PLAYER_SCREEN);
                PlayContent playContent =  JSON.parseObject(webSocketMessage.getMessageBody(), PlayContent.class);
                intent.putExtra(PLAYER_SCREEN,playContent);
                localBroadcastManager.sendBroadcast(intent);


            }else if(webSocketMessage.getMessageType().equals(CLOSE_SCREEN)){

                Intent intent = new Intent();
                intent.setAction(CLOSE_SCREEN);
                localBroadcastManager.sendBroadcast(intent);


            }



        }

    }


}
